package PlotPourri;

import PlotPourri.Database.DatabaseLMCi;
import Jama.Matrix;
import PlotPourri.BandName;
import PlotPourri.Star;
import java.io.File;

public class PCAold {

    public static void main(String[] args) {
        DatabaseLMCi starDatabase = new DatabaseLMCi(new File("E:\\Research\\Astrophysics\\LMC\\TypeI\\OG3.dat"));
        System.out.println(starDatabase.size());
        int order = 8;
        int points = 100;
        double[][] m = new double[starDatabase.keySet().size()][2 * order + 1];
        int counter = 0;
        //for (int name : starDatabase.keySet()) {
        //    Star star = starDatabase.get(name);
        //    double log10P = Math.log10(star.getPeriod());
        //    if (log10P < 0.4) continue;
        //    m[counter++] = star.getBand(BandName.I).get(0).getCoefficients(order);
        //}

        //Matrix evm = S.eig().getRealEigenvalues()//S.eig()..getD();
        //for (int i = 0; i < evm.getRowDimension(); i++)
        //    for (int j = 0; j < evm.getColumnDimension(); j++)
        //System.out.println(evm.get(i, j));

        //double[] evm = S.eig().getRealEigenvalues();//.getRealEigenvalues();//S.eig()..getD();
        //for (int j = 0; j < evm.length; j++)
        //    System.out.println(evm[j]);
        //double[][] m = new double[][];
        for (int name : starDatabase.keySet()) {
            Star star = starDatabase.get(name);
            double log10P = Math.log10(star.getPeriod());
            if (log10P < 0.4) continue;
            double[][] I = star.getBand(BandName.I).get(0).getShiftedData(order, points);
            double[] mags = new double[I.length];
            for (int i = 0; i < I.length; i++) mags[i] = I[i][1];
            m[counter++] = mags;
        }
        System.out.println("Done parsing");
        Matrix C = new Matrix(getC(m));
        System.out.println("Done making C");
        Matrix evm = C.eig().getD();
        for (int i = 0; i < evm.getRowDimension(); i++)
            for (int j = 0; j < evm.getColumnDimension(); j++)
                System.out.println(evm.get(i, j));
    }

    static double getMbar(int j, double[][] m) {
        double temp = 0;
        for (int i = 0; i < m.length; i++) if (j < m[i].length) temp += m[i][j];
        return temp / m.length;
    }

    static double getS(int j, double[][] m) {
        double temp = 0;
        for (int i = 0; i < m.length; i++) temp += Math.pow(m[i][j] - getMbar(j, m), 2);
        return Math.sqrt(temp / m.length);
    }

    static double[][] getC(double[][] m) {
        double[][] C = new double[m.length][100];
        for (int j = 0; j < C.length; j++) for (int k = 0; k < C[j].length; k++) C[j][k] = getC(j, k, m);
        return null;
    }

    static double getC(int j, int k, double[][] m) {
        double temp = 0;
        for (int i = 0; i < m.length; i++) temp += (m[i][j] - getMbar(j, m)) * (m[i][k] - getMbar(k, m)) / (getS(j, m) * getS(k, m));
        return temp / m.length;
    }
}
